package main

import (
	"fgo/advance/db/gorm/models"
	"github.com/google/martian/log"
)

func main() {
	log.SetLevel(log.Debug)
	db := models.NewDb()
	defer db.Close()

	user1 := models.User{}
	db.First(&user1)
	// SELECT * FROM `user`   ORDER BY `user`.`id` ASC LIMIT 1
	log.Infof("user1: (%v)", user1)

	user2 := models.User{}
	db.Last(&user2)
	// SELECT * FROM `user`   ORDER BY `user`.`id` DESC LIMIT 1
	log.Infof("user1: (%v)", user1)

	users1 := []models.User{}
	db.Find(&users1)
	// SELECT * FROM `user`
	log.Infof("users1: (%v)", users1)

	user3 := models.User{}
	// SELECT * FROM `user`  WHERE (`user`.`id` = 10) ORDER BY `user`.`id` ASC LIMIT 1
	db.First(&user3, 10)

	//// 查询多条数据的某一列
	var ages []int64
	db.Model(&models.User{}).Where("age > 998").Pluck("age", &ages)
	//  SELECT age FROM `user`  WHERE (age > 998)
	log.Infof("ages:(%v)", ages)

	//////////  Where查询条件 (简单SQL)
	user4 := models.User{}
	db.Where("name = ? AND age > ?", "jinzhu", 1).First(&user4)
	// SELECT * FROM `user`  WHERE (name = 'jinzhu' AND age > 1) ORDER BY `user`.`id` ASC LIMIT 1

	//// Where查询条件 (Struct & Map)
	user5 := models.User{}
	db.Where(&models.User{Name: "jinzhu", Age: 20}).First(&user5)
	//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 LIMIT 1;
	// Map
	users2 := []models.User{}
	db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users2)
	//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20;
	// 主键的Slice
	users3 := []models.User{}
	db.Where([]int64{20, 21, 22}).Find(&users3)
	//// SELECT * FROM users WHERE id IN (20, 21, 22);

}
